package silo.dungeonbuddy;

import java.net.ServerSocket;
import java.net.Socket;
import java.io.IOException;

public class MultiThreadedServer implements Runnable
{
    protected int serverPort = 9000;
    protected ServerSocket serverSocket = null;
    protected boolean isStopped = false;
    protected Thread runningThread = null;
    protected Start game;

    public MultiThreadedServer(Start game, int port)
    {
        this.serverPort = port;
        this.game = game;
    }//constructor

    public void run()
    {
        synchronized(this)
        {
            this.runningThread = Thread.currentThread();
        }
        openServerSocket();
        while(! isStopped())
        {
            Socket clientSocket = null;
            try
            {
                clientSocket = this.serverSocket.accept();
            }catch (IOException e)
            {
                if(isStopped())
                {
                    System.out.println("Server Stopped.") ;
                    return;
                }
                throw new RuntimeException("Error accepting client connection", e);
            }
            new Thread(new RunnableServer(game, clientSocket, "Multithreaded Server")).start();
        }
        System.out.println("Server Stopped.") ;
    }//run()


    private synchronized boolean isStopped()
    {
        return this.isStopped;
    }//isStopped()

    public synchronized void stop()
    {
        this.isStopped = true;
        try
        {
            this.serverSocket.close();
        } catch (IOException e)
        {
            throw new RuntimeException("Error closing server", e);
        }
    }//stop()

    private void openServerSocket()
    {
        try
        {
            this.serverSocket = new ServerSocket(this.serverPort);
        } catch (IOException e)
        {
            throw new RuntimeException("Cannot open port 8080", e);
        }
    }//openServerSocket()
}//class MultiThreadedServer